package com.ztom.top100;

/**
 * 二叉树的直径
 * <p>
 * https://leetcode-cn.com/problems/diameter-of-binary-tree/
 *
 * @author ZhangTao
 */
public class Code94DiameterOfBinaryTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }

        dfs(root);
        return max;
    }

    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int l = dfs(node.left);
        int r = dfs(node.right);
        max = Math.max(max, l + r);
        return Math.max(l, r) + 1;
    }
}
